<?php
namespace Addons\QyWechat\Controller\Api\Callback;
use Models\BaseModel as Model;
use Addons\QyWechat\Helper;
use Addons\Fission\Helper as FissionHelper;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\ProvidersApi;
require_once(DOXCX_FRAME_PATH . 'fun/library/QyWxCypto/WXBizMsgCrypt.php');

use Addons\WechatOpenPlatform\Services\Wxopenapi;
 
class Externalcontact extends \BaseController
{ 
	  public function  index(){
		  if(isset($_GET['echostr'])){
			  //接受验证数据 
		  	  $sVerifyMsgSig = $_GET['msg_signature'];
			  $sVerifyTimeStamp = $_GET['timestamp'];  
			  $sVerifyNonce = $_GET['nonce'];
			  $sVerifyEchoStr = $_GET['echostr'];
			  $configList = (new Model('qy_wechat_config'))->list_all();
			  foreach($configList as $config){
				  $encodingAesKey = $config->externalcontact_aes;
				  $token = $config->externalcontact_token;
				  $corpId = $config->corp_id; 
				  $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
				  // 需要返回的明文
				  $sEchoStr = "";
				  $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
				  if($errCode == 0){
					   echo $sEchoStr;
					   exit();
				  }
			  }
		  }else{
			  //搜集参数  
			  $sReqMsgSig = $_GET['msg_signature'];
			  $sReqTimeStamp = $_GET['timestamp'];
			  $sReqNonce = $_GET['nonce'];
			  //获取xml冰去除特殊字符 
			  $sReqData = preg_replace("/[\n\s]/", '', file_get_contents('php://input'));
			  //解密
			  $config = (new Model('qy_wechat_config'))->find(['corp_id'=>xml_to_array($sReqData)['ToUserName']]);
			  $encodingAesKey = $config->externalcontact_aes;
			  $token = $config->externalcontact_token;
			  $corpId = $config->corp_id;
			  $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
			  $sMsg = "";  // 解析之后的明文
			  $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
			  if ($errCode == 0) {
				  // 解密成功，sMsg即为xml格式的明文
				  // TODO: 对明文的处理
				  /*
				  "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
				  <FromUserName><![CDATA[mycreate]]></FromUserName>
				  <CreateTime>1409659813</CreateTime>
				  <MsgType><![CDATA[text]]></MsgType>
				  <Content><![CDATA[hello]]></Content>
				  <MsgId>4561255354251345929</MsgId>
				  <AgentID>218</AgentID>
				  </xml>"
				  */
				  $arr = xml_to_array($sMsg);
				  if($this->repeat_push($_GET["msg_signature"])){
				  	echo "success";
			 		exit();
				  }
					$_request = "";
				  if($arr['Event'] == 'change_external_contact'){
					  if($arr['ChangeType'] == 'add_external_contact'){
					  		$CorpID = $arr['ToUserName'];//企业微信CorpID
					  		$qyConfig = (new Model('qy_wechat_config'))->field("wid")->find(['corp_id'=>$CorpID]);
					  		$qyCustomer = (new Model('qy_externalcontact_list'))->field("id")->find(['wid'=>$qyConfig->wid,'external_userid'=>$arr['ExternalUserID']]);
					  		$arr["is_new"] = $qyCustomer->id?0:1;
						  	$this->add_external_contact($arr);
							\Lib\Hook::listen('add_external_contact', $_request, $arr);
					  }elseif($arr['ChangeType'] == 'edit_external_contact'){
						  $this->edit_external_contact($arr);
							\Lib\Hook::listen('edit_external_contact', $_request, $arr);
					  }elseif($arr['ChangeType'] == 'del_external_contact'){
						  $this->del_external_contact($arr);
						\Lib\Hook::listen('del_external_contact', $_request, $arr);
					  }elseif($arr['ChangeType'] == 'del_follow_user'){
						  $this->del_follow_user($arr);
						\Lib\Hook::listen('del_follow_user', $_request, $arr);
					  }
				  }elseif($arr['Event'] == 'change_external_chat'){
					  if($arr['ChangeType'] == 'create'){
					  	$this->change_external_chat($arr);
						\Lib\Hook::listen('change_external_chat', $_request, $arr);
					  }elseif($arr['ChangeType'] == 'update'){
					  	$this->change_external_chat($arr);
						\Lib\Hook::listen('change_external_chat', $_request, $arr);
					  }elseif ($arr['ChangeType'] == 'dismiss') {
					  	$this->delete_external_chat($arr);
						\Lib\Hook::listen('delete_external_chat', $_request, $arr);
					  }
				  }
			  } else {
				  diy_log("解密失败ERR: " . $errCode . "\n\n");
			  }
			  echo "success";
			  exit();
		  }
	  }  
	  
	  //添加企业客户
	  public function add_external_contact($arr){
		  $this->import_et_dynamic(1,$arr);
		  $this->import_et_data($arr); 
	  }
	  
	  function GetRandStr($length){
		$str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$len=strlen($str)-1;
		$randstr='';
		for($i=0;$i<$length;$i++){
		$num=mt_rand(0,$len);
		$randstr .= $str[$num];
		}
		return $randstr;
		}
	  
	  
	  public function import_et_data($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  //获取客户详情 导入数据
		  $customer_info_res = $etApp->external_contact->get($arr['ExternalUserID']);
		  if($customer_info_res['errcode'] == 0){
		  		$qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
				$customer_info = $customer_info_res;
				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
				$user = '';
				$tags = [];
				foreach($customer_info['follow_user'] as $followuser){
					if($qyUser->userid == $followuser['userid']){
						$user = $followuser;
						foreach($followuser['tags'] as $ftag){
							$tags[] = $ftag['tag_id'];
						}
					}
				}	

				$qyCustomer->wid = $qyConfig->wid;
				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
				$qyCustomer->name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name']);
				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
				$qyCustomer->type = $customer_info['external_contact']['type'];
				$qyCustomer->gender = $customer_info['external_contact']['gender'];
				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
				$qyCustomer->position = $customer_info['external_contact']['position'];
				$qyCustomer->corp_name = $customer_info['external_contact']['corp_name'];
				$qyCustomer->corp_full_name = $customer_info['external_contact']['corp_full_name'];
				$qyCustomer->external_profile = json_encode($customer_info['external_contact']['external_profile']);
				$qyCustomer->user_id = $qyUser->id;
				$qyCustomer->remark = Helper::getInstance()->filterEmoji($user['remark']);
				$qyCustomer->description = $user['description'];
				$qyCustomer->createtime = $user['createtime'];
				$qyCustomer->tags_info = json_encode($user['tags']);
				$qyCustomer->tags = json_encode($tags);
				$qyCustomer->remark_corp_name = $user['remark_corp_name'];
				$qyCustomer->remark_mobiles = json_encode($user['remark_mobiles'],320);
				$qyCustomer->add_way = $user['add_way'];
				$qyCustomer->oper_userid = $user['oper_userid'];
				$qyCustomer->state = $user['state'];
				$qyCustomer->status = 0;
				$qyCustomer->save();	
		  }
		  return $qyCustomer;
	  }
	  
	  
	  public function edit_external_contact($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  //获取客户详情 导入数据
		  $customer_info_res = $etApp->external_contact->get($arr['ExternalUserID']);
		  if($customer_info_res['errcode'] == 0){
		  		$qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
				$customer_info = $customer_info_res;
				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
				$user = '';
				$tags = [];
				foreach($customer_info['follow_user'] as $followuser){
					if($qyUser->userid == $followuser['userid']){
						$user = $followuser;
						foreach($followuser['tags'] as $ftag){
							$tags[] = $ftag['tag_id'];
						}
					}
				}	

				$qyCustomer->wid = $qyConfig->wid;
				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
				$qyCustomer->name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name']);
				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
				$qyCustomer->type = $customer_info['external_contact']['type'];
				$qyCustomer->gender = $customer_info['external_contact']['gender'];
				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
				$qyCustomer->position = $customer_info['external_contact']['position'];
				$qyCustomer->corp_name = $customer_info['external_contact']['corp_name'];
				$qyCustomer->corp_full_name = $customer_info['external_contact']['corp_full_name'];
				$qyCustomer->external_profile = json_encode($customer_info['external_contact']['external_profile']);
				$qyCustomer->user_id = $qyUser->id;
				$qyCustomer->remark = Helper::getInstance()->filterEmoji($user['remark']);
				$qyCustomer->description = $user['description'];
				$qyCustomer->createtime = $user['createtime'];
				$qyCustomer->tags_info = json_encode($user['tags']);
				$qyCustomer->tags = json_encode($tags);
				$qyCustomer->remark_corp_name = $user['remark_corp_name'];
				$qyCustomer->remark_mobiles = json_encode($user['remark_mobiles'],320);
				$qyCustomer->add_way = $user['add_way'];
				$qyCustomer->oper_userid = $user['oper_userid'];
				$qyCustomer->state = $user['state'];
				$qyCustomer->status = 0;
				$qyCustomer->save();			
		  }
	  }

	  public function del_external_contact($arr){
		  $this->import_et_dynamic(2,$arr);
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  $qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$arr['ExternalUserID']]);
		  if(!$qyCustomer->id){
			  return;
		  }
		  $qyCustomer->status = 1;
		  $qyCustomer->deltime = time();
		  $qyCustomer->save();
	  }
	  
	  public function del_follow_user($arr){
		  $this->import_et_dynamic(3,$arr);
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  $qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$arr['ExternalUserID']]);
		  if(!$qyCustomer->id){
			  return;
		  }
		  $qyCustomer->status = 2;
		  $qyCustomer->deltime = time();
		  $qyCustomer->save();
	  }
	  //客户群变更事件
	  public function change_external_chat(&$arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  //获取群详情
		  $groupChatInfoRes = $QyWechatApi->get_et_groupchat_info($arr['ChatId'],$qyConfig->wid);
		  if($groupChatInfoRes['errcode'] == 0){
			  $groupChatInfo = $groupChatInfoRes['group_chat'];
			  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$groupChatInfo['owner']]);
			  $etGroupchat = (new Model('qy_et_groupchat'))->find(['wid'=>$qyConfig->wid,'chat_id'=>$arr['ChatId']]);
			  $oldMemberList = [];
			  if($etGroupchat->id){
			  	 $oldMemberList = array_column(json_decode($etGroupchat->member_list,1),'userid');
			  }
			  $memberList = json_decode($etGroupchat->member_list,1);
			  $etGroupchat->wid = $qyConfig->wid;
			  $etGroupchat->chat_id = $groupChatInfo['chat_id'];
			  $etGroupchat->name = $groupChatInfo['name'];
			  $etGroupchat->user_id = $qyUser->id;
			  $etGroupchat->create_time = $groupChatInfo['create_time'];
			  $etGroupchat->notice = $groupChatInfo['notice'];
			  $etGroupchat->member_list = json_encode($groupChatInfo['member_list']);
			  $etGroupchat->save();
			  $useridList = [];
			  foreach($memberList as $v){
				  $useridList[] = $v['userid'];
			  }
			  $newMem = [];
			  foreach($groupChatInfo['member_list'] as $member){
			  	  //新进群非企业成员
			  	  if($arr['UpdateDetail']=="add_member" && $member['type'] == 2 && !in_array($member['userid'],$oldMemberList)){
			  	  	  $newMem[] = $member;
			  	  }
				  if($member['type'] == 2 && !in_array($member['userid'],$useridList)){
					  $arr['ExternalUserID'] = $member['userid'];
					  $this->import_et_dynamic(4,$arr);
				  }
			  }
			  $arr['new_member'] = $newMem;
		  }
	  }
	  //客户群删除事件
	  public function delete_external_chat($arr){
	  	$etGroupchat = (new Model('qy_et_groupchat'))->find(['chat_id'=>$arr['ChatId']]);
	  	if($etGroupchat->id){
			$etGroupchat->remove();
	  	}
	  }
	  
	  public function del_expire_fission($fission){
		 $wid = $fission->wid;
		 $QyWechatApi = QyWechatApi::getInstance();
		 $qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		 $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		 
		 if($fission->id && time() > $fission->end_time){
			 $deleteRes = $etApp->contact_way->delete($fission->config_id?$fission->config_id:'');
			 $fusers = (new Model('qy_fission_user'))->where(['wid'=>$wid,'fid'=>$fission->id])->list_all();
			 foreach($fusers as $fuser){
				 if($fuser->config_id){
					 $etApp->contact_way->delete($fuser->config_id);
				 }
			}
		 }
	  }
	   
	  public function import_et_dynamic($type,$data){
		  $CorpID = $data['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $etDynamic = new Model('qy_et_dynamic');
		  $etDynamic->wid = $qyConfig->wid;
		  $etDynamic->ctime = time();
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$data['UserID']]);
		  if($type == 1 || $type == 2 || $type == 3){
			  $etDynamic->external_userid = $data['ExternalUserID'];
			  $etDynamic->type = $type;
			  $etDynamic->user_id = $qyUser->id;
		  }elseif($type == 4){
			  $etDynamic->external_userid = $data['ExternalUserID'];
			  $etDynamic->type = $type;
			  $etDynamic->chat_id = $data['ChatId'];
		  }
		  $etDynamic->save();
	  }

	  public function repeat_push($msg_signature){
	  	$createTime = $msg_signature;
	  	$folderPath = pub_path('wechatPushRecord');
	  	is_dir($folderPath) or mkdir($folderPath, 0777, true);
	  	$filePath = $folderPath.'/externalcontact.txt';
	  	if(file_exists($filePath) && filesize($filePath) > 10485760) unlink($filePath);
	  	$arr =  json_decode(file_get_contents($filePath),1)?json_decode(file_get_contents($filePath),1):[];
	  	if(in_array($createTime,$arr)){
	  		return 1;//重复推送
	  	}else{
	  		array_push($arr,$createTime);//添加元素
	  		file_put_contents($filePath, json_encode($arr));
	  	}
	  	return 0;//未重复
	  }
	 
}
